//
//  UIView+main.m
//  ClassMusic
//
//  Created by ChinaRainbow-iOS on 2018/2/7.
//  Copyright © 2018年 ChinaRainbow-iOS. All rights reserved.
//

#import "UIView+main.h"
#import "UIColor+main.h"
#import <objc/runtime.h>

@implementation UIView (main)

    //MARK:frame
- (float)boundsWidth{
    return self.bounds.size.width;
}

- (float)boundsHeight{
    return self.bounds.size.width;
}

- (void)setBoundsWidth:(float)w{
    CGRect frame = self.bounds;
    frame.size.width = w;
    self.bounds = frame;
}

- (void)setBoundsHeight:(float)h{
    CGRect frame = self.bounds;
    frame.size.height = h;
    self.bounds = frame;
}

- (float)ccx{
    return self.frame.origin.x;
}

- (float)ccy{
    return self.frame.origin.y;
}

- (float)ccwidth{
    return self.frame.size.width;
}
- (float)ccheight{
    return self.frame.size.height;
}

- (void)setccX:(float)x{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (void)setccY:(float)y{
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (void)setccWidth:(float)w{
    CGRect frame = self.frame;
    frame.size.width = w;
    self.frame = frame;
}

- (void)setccHeight:(float)h{
    CGRect frame = self.frame;
    frame.size.height = h;
    self.frame = frame;
}

- (CGFloat)centerX {
    return self.center.x;
}

- (void)setCenterX:(CGFloat)centerX {
    self.center = CGPointMake(centerX, self.center.y);
}

- (CGFloat)centerY {
    return self.center.y;
}

- (void)setCenterY:(CGFloat)centerY {
    self.center = CGPointMake(self.center.x, centerY);
}

- (CGPoint)origin {
    return self.frame.origin;
}

- (void)setOrigin:(CGPoint)origin {
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}

- (CGSize)size {
    return self.frame.size;
}

- (void)setSize:(CGSize)size {
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}
- (CGFloat)left {
    return self.frame.origin.x;
}

- (void)setLeft:(CGFloat)x {
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (CGFloat)top {
    return self.frame.origin.y;
}

- (void)setTop:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setRight:(CGFloat)right {
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}

- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (void)setBottom:(CGFloat)bottom {
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}

- (CGPoint)convertPoint:(CGPoint)point toViewOrWindow:(UIView *)view {
    if (!view) {
        if ([self isKindOfClass:[UIWindow class]]) {
            return [((UIWindow *)self) convertPoint:point toWindow:nil];
        } else {
            return [self convertPoint:point toView:nil];
        }
    }
    
    UIWindow *from = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
    UIWindow *to = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
    if ((!from || !to) || (from == to)) return [self convertPoint:point toView:view];
    point = [self convertPoint:point toView:from];
    point = [to convertPoint:point fromWindow:from];
    point = [view convertPoint:point fromView:to];
    return point;
}

    //MARK:function
    //垂直抖动
- (void)startVerticalShake
{
    CAKeyframeAnimation *keyAn = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    NSArray *array = [[NSArray alloc] initWithObjects:
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y-15)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y+13)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y-11)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y+9)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y-7)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y+5)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y-3)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y+1)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      nil];
    [keyAn setValues:array];
    keyAn.duration = 1.5f;
    keyAn.values = array;
        //    keyAn.delegate = self;
    keyAn.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
    [self.layer addAnimation:keyAn forKey:@"VerticalShake"];
}

    //水平抖动
- (void)startHorizontalShake
{
    [self becomeFirstResponder];
    
    CAKeyframeAnimation *keyAn = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [keyAn setDuration:0.5f];
    NSArray *array = [[NSArray alloc] initWithObjects:
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x-15, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x+15, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x-15, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x+15, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x-15, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x+15, self.center.y)],
                      [NSValue valueWithCGPoint:CGPointMake(self.center.x, self.center.y)],
                      nil];
    [keyAn setValues:array];
    
    NSArray *times = [[NSArray alloc] initWithObjects:
                      [NSNumber numberWithFloat:0.1f],
                      [NSNumber numberWithFloat:0.2f],
                      [NSNumber numberWithFloat:0.3f],
                      [NSNumber numberWithFloat:0.4f],
                      [NSNumber numberWithFloat:0.5f],
                      [NSNumber numberWithFloat:0.6f],
                      [NSNumber numberWithFloat:0.7f],
                      [NSNumber numberWithFloat:0.8f],
                      [NSNumber numberWithFloat:0.9f],
                      [NSNumber numberWithFloat:1.0f],
                      nil];
    [keyAn setKeyTimes:times];
    [self.layer addAnimation:keyAn forKey:@"HorizontalShake"];
}

    //添加动画遮罩 并在duration秒之后移除
- (void)addMaskViewWithDuration:(int)duration
{
    UIView *maskView = [[UIView alloc] initWithFrame:self.bounds];
    maskView.backgroundColor = [UIColor clearColor];
    [self addSubview:maskView];
    [maskView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:duration];
}

- (void)removeAllSubview
{
    for (UIView *item in self.subviews) {
        [item removeFromSuperview];
    }
}

- (UIView *)findFirstResponder
{
    if (self.isFirstResponder) {
        return self;
    }
    
    for (UIView *subView in self.subviews) {
        UIView *firstResponder = [subView findFirstResponder];
        
        if (firstResponder != nil) {
            return firstResponder;
        }
    }
    
    return nil;
}

#pragma mark - 获取父 viewController
- (UIViewController *)nearestViewController
{
    UIViewController *viewController = nil;
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            viewController = (UIViewController*)nextResponder;
            break;
        }
    }
    return viewController;
}

- (UITableView *)nearestTableView
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UITableView class]]) {
            return (UITableView *)nextResponder;
        }
    }
    return nil;
}

-(UIScrollView *)nearestScrollView
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIScrollView class]]) {
            return (UITableView *)nextResponder;
        }
    }
    return nil;
}

+ (UIView *)titileViewWithTitle:(NSString *)title activity:(BOOL)activity
{
    UILabel *bigLabel = [[UILabel alloc] init];
    bigLabel.text = title;
    bigLabel.backgroundColor = [UIColor clearColor];
    bigLabel.textColor = [UIColor blackColor];
    bigLabel.font = [UIFont boldSystemFontOfSize:17];
    bigLabel.adjustsFontSizeToFitWidth = YES;
    [bigLabel sizeToFit];
    
    CGRect rect = bigLabel.frame;
    UIView *titleView = [[UIView alloc] initWithFrame:rect];
    titleView.backgroundColor = [UIColor clearColor];
    
    if (activity) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        CGRect activityRect = activityView.bounds;
        activityRect.origin.y = (rect.size.height-activityRect.size.height)/2;
        activityView.frame = activityRect;
        [titleView addSubview:activityView];
        
        rect.origin.x = activityRect.size.width+5;
        bigLabel.frame = rect;
    }
    [titleView addSubview:bigLabel];
    
    CGRect titleFrame = CGRectMake(0, 0, 0, rect.size.height);
    titleFrame.size.width = rect.origin.x+rect.size.width;
    titleView.frame = titleFrame;
    
    return titleView;
}

+ (UIView *)titileViewWithTitle:(NSString *)title image:(UIImage *)image
{
    UILabel *bigLabel = [[UILabel alloc] init];
    bigLabel.text = title;
    bigLabel.backgroundColor = [UIColor clearColor];
    bigLabel.textColor = [UIColor blackColor];
    bigLabel.font = [UIFont boldSystemFontOfSize:17];
    bigLabel.adjustsFontSizeToFitWidth = YES;
    [bigLabel sizeToFit];
    
    CGRect rect = bigLabel.frame;
    UIView *titleView = [[UIView alloc] initWithFrame:rect];
    titleView.backgroundColor = [UIColor clearColor];
    [titleView addSubview:bigLabel];
    
    if (image) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        CGRect imageRect = CGRectMake(0, 0, 15, 15);
        imageRect.origin.x = rect.size.width+rect.origin.x+3;
        imageRect.origin.y = (rect.size.height-imageRect.size.height)/2;
        imageRect.size.width = image.size.width/(image.size.height/imageRect.size.height);
        imageView.frame = imageRect;
        [titleView addSubview:imageView];
        
        CGRect titleFrame = CGRectMake(0, 0, 0, rect.size.height);
        titleFrame.size.width = imageRect.origin.x+imageRect.size.width;
        titleView.frame = titleFrame;
    }
    
    return titleView;
}

    //去掉 json 中的多余的 null
+ (id)cleanJsonToObject:(id)data {
    NSError *error;
    if (data == (id)[NSNull null]) {
        return [[NSObject alloc] init];
    }
    id jsonObject;
    if ([data isKindOfClass:[NSData class]]) {
        jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    }
    else {
        jsonObject = data;
    }
    if ([jsonObject isKindOfClass:[NSArray class]]) {
        NSMutableArray *array = [jsonObject mutableCopy];
        for (int i = (int)(array.count - 1); i >= 0; i--) {
            id a = array[i];
            if (a == (id)[NSNull null]) {
                [array removeObjectAtIndex:i];
            } else {
                array[i] = [self cleanJsonToObject:a];
            }
        }
        return array;
    } else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *dictionary = [jsonObject mutableCopy];
        for (NSString *key in[dictionary allKeys]) {
            id d = dictionary[key];
            if (d == (id)[NSNull null]) {
                dictionary[key] = @"";
            } else {
                dictionary[key] = [self cleanJsonToObject:d];
            }
        }
        return dictionary;
    }
    else {
        return jsonObject;
    }
}

- (void)showShadow
{
        //加阴影
    self.layer.shadowColor = [UIColor zg_000000Color].CGColor;
    self.layer.shadowOffset = CGSizeMake(0,4);
    self.layer.shadowOpacity = 0.1;
    self.layer.shadowRadius = 8;
}

- (CGFloat)cornerRadius
{
    return [objc_getAssociatedObject(self, @selector(cornerRadius)) floatValue];
}

- (void)setCornerRadius:(CGFloat)cornerRadius
{
    self.layer.cornerRadius = cornerRadius;
    self.layer.masksToBounds = (cornerRadius > 0);
}

- (BOOL)avatarCorner{
    return [objc_getAssociatedObject(self, @selector(cornerRadius)) floatValue] > 0;
}

- (void)setAvatarCorner:(BOOL)corner{
    if (corner){
        self.layer.cornerRadius = CGRectGetWidth(self.frame)/2;
        self.layer.masksToBounds = corner;
    }
}

- (CGFloat)borderWidth{
    return [objc_getAssociatedObject(self, @selector(borderWidth)) floatValue];
}

- (void)setBorderWidth:(CGFloat)borderWidth{
    self.layer.borderWidth = borderWidth;
    self.layer.masksToBounds = (borderWidth > 0);
}


- (UIColor *)borderColor{
    return objc_getAssociatedObject(self, @selector(borderColor));
}

- (void)setBorderColor:(UIColor *)borderColor{
    self.layer.borderColor = borderColor.CGColor;
}


+ (__kindof UIView *)MQLoadNibView{
    NSString *className = NSStringFromClass([self class]);
    return [[[UINib nibWithNibName:className bundle:nil] instantiateWithOwner:self options:nil] lastObject];
}


-(void)MQViewSetCornerRadius:(CGFloat)radius{
    [self.layer setMasksToBounds:YES];
    [self.layer setCornerRadius:radius];
}
-(void)MQSetViewCircleWithBorderWidth:(CGFloat) width andColor:(UIColor *)borColor{
    [self MQViewSetCornerRadius:(self.frame.size.height/2)];
    self.layer.borderWidth=width;
    self.layer.borderColor=[borColor CGColor];
}
@end
